﻿using System;
using System.Collections.Generic;
using System.Windows.Input;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace WpfLob.Frame
{
    public class Presenter : IPresenter
    {
        private ObservableCollection<Pane> _panes = new ObservableCollection<Pane>();
        private int _currentPaneIndex = -1;

        public string Title
        {
            get { return _panes[CurrentPaneIndex].Title; }
        }

        public IEnumerable<Pane> Panes
        {
            get { return _panes; }
        }

        public PanePosition PositionOf(Pane pane)
        {
            int index = _panes.IndexOf(pane);
            return
                index < CurrentPaneIndex ? PanePosition.Backward :
                index > CurrentPaneIndex ? PanePosition.Forward :
                    PanePosition.Top;
        }

        public void Show(Pane pane)
        {
            UnbindPaneTitle();

            // Pop all forward panes off the stack.
            while (CurrentPaneIndex < _panes.Count - 1)
                _panes.RemoveAt(CurrentPaneIndex + 1);

            // Push this pane at the top of the stack.
            _panes.Add(pane);
            CurrentPaneIndex++;

            BindPaneTitle();
        }

        public void GoBackTo(Pane pane)
        {
            CurrentPaneIndex = _panes.IndexOf(pane);
        }

        public int CurrentPaneIndex
        {
            get { return _currentPaneIndex; }
            set
            {
                _currentPaneIndex = value;
                FirePropertyChanged("CurrentPaneIndex");
                FirePropertyChanged("Title");
            }
        }

        internal void UnbindPaneTitle()
        {
            if (CurrentPaneIndex >= 0)
                _panes[CurrentPaneIndex].PropertyChanged -= PanePropertyChanged;
        }

        internal void BindPaneTitle()
        {
            _panes[CurrentPaneIndex].PropertyChanged += PanePropertyChanged;
        }

        private void PanePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Title")
                FirePropertyChanged("Title");
        }
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void FirePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}
